<?php

namespace App\Http\Middleware;

use Closure;

class HomeTokenVerify
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $token  = $request->header('Token')?$request->header('Token'):'';
        $lang  = $request->header('Lang')?$request->header('Lang'):'zn';
        $langua = config('lang.NATION');
        try{
            if(!$token){ //判断有无token返回，若无，则返回错误响应
                return response()->json([
                    'code'=>50000,
                    'message'=>$langua['LOGIN_NOT'][$lang]
                ]);
            }else{
                $data = decrypt($token);
                $time = time();
                if($data['expire']<$time){
                    return response()->json([
                        'code'=>50002,
                        'message'=>$langua['LOGIN_EXPIRE'][$lang]
                    ]);
                }else{
                    $request->token = $token;
                    $request->lang = $lang;
                    return $next($request);
                }
            }
        }catch (\Exception $e){
            return response()->json([
                'code'=>50001,
                'message'=>$langua['LOGIN_ERROR'][$lang]
            ]);
        }
    }
}
